package com.tensquare.spit.service;

import com.tensquare.spit.dao.SpitDao;
import com.tensquare.spit.pojo.Spit;
import entity.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.CriteriaDefinition;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import utils.IdWorker;

import java.util.List;

@Service
public class SpitService {
    @Autowired
    private SpitDao spitDao;
    @Autowired
    private IdWorker idWorker;
    @Autowired
    private MongoTemplate mongoTemplate;
    //1.查所有
    public List<Spit> findAll() {
        return spitDao.findAll();
    }
    //2.查单个
    public Spit findById(String spitId) {
        return spitDao.findById(spitId).get();
    }
    //3.增加
    public void add(Spit spit) {
        spit.set_id(idWorker.nextId()+"");
        spitDao.insert(spit);
    }
    //4.修改
    public void update(Spit spit) {
        spitDao.save(spit);
    }
    //5.删除
    public void deleteById(String spitId) {
        spitDao.deleteById(spitId);
    }
    //6.根据parentId查询
    public PageResult findByParentId(String parentid, int page, int size) {
        Page<Spit> spitPage = spitDao.findByParentid(parentid, PageRequest.of(page-1, size));
        return new PageResult(spitPage.getTotalElements(),spitPage.getContent());
    }
    //7.吐槽点赞
    public void thumbup(String spitId) {
        //7.1查询条件
        Query query=new Query();
        query.addCriteria(new Criteria("_id").is(spitId));
        //7.2修改条件
        Update update=new Update();
        update.inc("thumbup",1);
        //7.3开始修改
        mongoTemplate.updateFirst(query,update,"spit");
    }
}
